#include <iostream>
#include <unistd.h>
#include <fcntl.h>
#include <cstdio>
#include <cerrno>
#include <cstring>

using std::cout;
using std::endl;


// int main()
// {
//     char buffer[1024];
//     while(1)
//     {
//         printf("Please Enter_> ");
//         fflush(stdout);//stdout
//         ssize_t n = read(0, buffer, sizeof(buffer) - 1);//从默认输入读取数据至buffer; -1是为了存放'\0'标记字符串结尾

//         if(n > 0)
//         {
//             //读成功,read会返回读取到的字节个数
//             buffer[n] = '\0';
//             cout << "buffer: " << buffer << endl;
//         }
//         else if(n == 0)
//         {
//             //写端关闭、ctrl D结束进程
//             cout << "read done" << endl;
//             break;
//         }
//         else{
//             //err
//             std::cerr << "read error" << endl;
//             break;
//         }
//     }
//     return 0;
// }


void SetNonBlock(int fd)
{
    //调用该函数，将read需要的stdin输入资源，逻辑从阻塞换为非阻塞
    int fl = fcntl(fd, F_GETFL);
    if(fl < 0)
    {
        std::cerr << "fl error" << endl;
        return;
    }
    fcntl(fd, F_SETFL, fl | O_NONBLOCK); // 可以从open打开文件时就可以创建为后续工作模式为“非阻塞”
    cout << "fd changed O_NONBLOCK done" << endl;
}
int main()
{
    char buffer[1024];
    SetNonBlock(0);
    sleep(1);
    while(1)
    {
        //printf("Please Enter_> ");
        //fflush(stdout);//stdout
        ssize_t n = read(0, buffer, sizeof(buffer) - 1);//从默认输入读取数据至buffer; -1是为了存放'\0'标记字符串结尾

        if(n > 0)
        {
            //读成功,read会返回读取到的字节个数
            buffer[n] = '\0';
            cout << "buffer: " << buffer << endl;
        }
        else if(n == 0)
        {
            //写端关闭、ctrl D结束进程
            cout << "read done" << endl;
            break;
        }
        else{
            if(errno == EWOULDBLOCK)
            {
                //err
                std::cerr << "read error, n = " << n << ", errno code : " << errno << ", error string: " << strerror(errno) << endl;
                //break;
                sleep(1);
            }else{
                std::cerr << "read error" << endl;
                break;
            }

        }
    }
    return 0;
}